package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.db.domain.MarketAdminExample;
import com.cskaoyan.market.db.mapper.MarketAdminMapper;
import com.cskaoyan.market.service.AdminProfileService;
import com.cskaoyan.market.util.MybatisUtils;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:yanzijun
 * @time:2024/06/20/11:17
 */
public class AdminProfileServiceImpl implements AdminProfileService {

    @Override
    public int password(String username, String oldPassword, String newPassword, String newPassword2) {
        SqlSession session = MybatisUtils.getSession();
        MarketAdminMapper mapper = session.getMapper(MarketAdminMapper.class);
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        MarketAdmin marketAdmin = mapper.selectOneByExample(marketAdminExample);
        //输入的原密码与数据库中的原密码不相同
        if (!marketAdmin.getPassword().equals(oldPassword)) {
            return 1;
        }
        // 输入的密码为空
        if (StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(newPassword2)) {
            return 2;
        }
        //输入的新密码与原密码一样
        if (newPassword.equals(oldPassword)) {
            return 3;
        }
        //输入的密码格式不对
        Pattern passwordPattern = Pattern.compile("^((?=\\S*?[A-Z])(?=\\S*?[a-z])(?=\\S*?[0-9]).{6,})\\S$");
        Matcher passwordMatcher = passwordPattern.matcher(newPassword);
        if (!passwordMatcher.find()) {
            return 4;
        }
        //两次密码输入不一致
        if (!newPassword.equals(newPassword2)) {
            return 5;
        } else {
            //新输入的两次密码相同且格式相同
            //可以对数据库进行修改
            marketAdmin.setPassword(newPassword);
            mapper.updateByExampleSelective(marketAdmin, marketAdminExample);
            session.commit();
            session.close();
            return 0;
        }
    }
}
